package com.example.ui.homepage;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;

import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.net.Communication;
import com.example.service.MainService;
import com.example.ui.leftmenu.LeftMenuView;
import com.example.util.Util;

public class SetHeadActivity extends Activity implements OnClickListener{
	Button cameraBtn,photoAlbumBtn,cancelBtn;
	LinearLayout layout;

	private String Filename = "";
	private String imagenames = "";
	
	public static Handler handler;
	Bitmap photo;
	
	private Intent myIntent;
	private String myId;
	private SharedPreferences sp;
	private Editor spEditor;
	
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.set_head);
		myIntent = getIntent();
		myId = myIntent.getStringExtra("myId");
		findView();
		click();
		handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					
					Util.toast(SetHeadActivity.this, "上传成功");
//					Drawable dra = new BitmapDrawable(photo);
					HomePageView.headImg.setImageBitmap(photo);
					LeftMenuView.titleImg.setImageBitmap(photo);
					MyInformationActivity.imgHead.setImageBitmap(photo);
					Communication.getHead(HSApplication.sp.getString("userid","").toString());
					HomePageView.homePageAdapter.notifyDataSetChanged();
					finish();
					break;
				case 1:
					Util.toast(SetHeadActivity.this, "上传失败");
					break;
				case 2:
					Util.toast(SetHeadActivity.this, "请检查您的网络连接");
					break;

				default:
					break;
				}
				super.handleMessage(msg);
			}
		};
	}
	
	private void findView() {
		cameraBtn = (Button)findViewById(R.id.set_head_camera_btn);
		photoAlbumBtn = (Button)findViewById(R.id.set_head_album_btn);
		cancelBtn=(Button)findViewById(R.id.set_head_cancel_btn);
		layout=(LinearLayout)findViewById(R.id.set_head_layout);
		cameraBtn.setOnClickListener(this);
		photoAlbumBtn.setOnClickListener(this);
		cancelBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.set_head_camera_btn://=====拍照
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			// 获得名字
			imagenames = UUID.randomUUID() + ".jpg";
			Filename = Environment.getExternalStorageDirectory() + "/" + imagenames;
			// 下面这句指定调用相机拍照后的照片存储的路径
			intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(Filename)));
			startActivityForResult(intent, 1);
			break;
		case R.id.set_head_album_btn://=====相册
			Intent album = new Intent(Intent.ACTION_GET_CONTENT);
			album.setType("image/*");
			startActivityForResult(album, 2);
			break;
		case R.id.set_head_cancel_btn:
			finish();
			break;

		default:
			break;
		}
	}
	
	private void click(){
		layout.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if(event.getAction()==MotionEvent.ACTION_DOWN){
					finish();
				}
				return true;
			}
		});
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if(requestCode==1){
			startPhotoZoom(Uri.fromFile(new File(Filename)));
			
		}else if(requestCode==2){
			
			if(data!=null){
				
				Uri uri = data.getData();//可以得到图片在Content：//。。。中的地址，把它转化成绝对地址如下
				String[] proj = {MediaStore.Images.Media.DATA};
				
				//参数：proj 是指查哪一列
				Cursor cursor = managedQuery(uri, proj,null, null, null);

				if(cursor != null){
					int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					if(cursor.getCount()>0 && cursor.moveToFirst()){
						Filename = cursor.getString(column_index);
						String name = Filename.substring(Filename.lastIndexOf("/"));
						imagenames = System.currentTimeMillis()+name.substring(name.indexOf("."));
						
						startPhotoZoom(data.getData());
					}
					
				}
				
			}
			
		}else if (requestCode == 3) {
			/**
			 * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃
			 * 当前功能时，会报NullException，可以根据不同情况在合适的 地方做判断处理类似情况
			 * 
			 */
			if (data != null) {
				try {
					setPicToView(data);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} else{
			finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	
	
	/**
	 * 剪裁图片的方法
	 * 
	 * @param uri
	 */
	private void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	
	

	/**
	 * 保存剪裁之后的图片
	 * 
	 * @param picdata
	 * @throws IOException
	 */
	private void setPicToView(Intent picdata) throws IOException {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			photo = extras.getParcelable("data");
			// 压缩
			photo = imageZoom(photo);
			File f1 = new File(getCacheDir(), imagenames);
			Filename = getCacheDir() + "/" + imagenames;
			savePic(photo, f1.getPath());
			//上传头像
			Communication.uploadHead(SetHeadActivity.this, myId, Filename);
			
		}

	}

	public Bitmap imageZoom(Bitmap bitMap) {
		// 图片允许最大空间 ：单位：KB
		double maxSize = 200.00;
		// 将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitMap.compress(Bitmap.CompressFormat.JPEG,70,baos);//70 -- 压缩率 ；  100是不压缩、压缩率为0；
		byte[] b = baos.toByteArray();

		// 将字节换成KB
		double mid = b.length / 1024;
		// 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
		if (mid > maxSize) {
			// 获取bitmap大小 是允许最大大小的多少倍
			double i = mid / maxSize;
			// 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
			// （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
			bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
					bitMap.getHeight() / Math.sqrt(i));
			return bitMap;
		}

		return bitMap;
	}

	public static void savePic(Bitmap b, String strFileName) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(strFileName);
			if (null != fos) {
				b.compress(Bitmap.CompressFormat.PNG, 70, fos);
				fos.flush();
				fos.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/***
	 * 图片的缩放方法
	 * 
	 * @param bgimage
	 *            ：源图片资源
	 * @param newWidth
	 *            ：缩放后宽度
	 * @param newHeight
	 *            ：缩放后高度
	 * @return
	 */
	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
			double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

	

}
